<?php


namespace App\Http\Repositories\UserCenter;
use App\Exceptions\ApiException;
use App\Http\Middleware\Authenticate;
use App\Http\Repositories\BaseRepository as Repository;
use App\Models\UserModels\Models\AdminModel;

class AdminRepository extends Repository
{
    public $admin;
    public function __construct(AdminModel $admin)
    {
        $this->admin = $admin;
    }

    /**
     * 获取用户详情
     * @param $data
     * @return array|mixed
     * @throws ApiException
     */
    public function getAdminInfo($data)
    {
        $where = [];
        if (isset($data['id'])) {
            $where['id'] = $data['id'];
        } elseif (isset($data['uuid'])) {
            $where['member_uuid'] = $data['uuid'];
        }

        return $this->admin->getAdminInfo($where);

    }

    /**
     * 添加用户
     * @param $data
     * @return mixed
     * @throws ApiException
     */
    public function addAdmin($data)
    {
        $where['name'] = $data['name'];
        if ($this->admin->handleCondition($where)->first()) {
            throw new ApiException([0, '用户名已注册']);
        }

        if (is_real_exists(@$data['member_email'])) {
            if ($this->admin->handleCondition(['member_email' => $data['member_email']])->first()) {
                throw new ApiException([0, '邮箱已注册']);
            }
        }

        if (is_real_exists(@$data['member_phone'])) {
            if ($this->admin->handleCondition(['member_phone' => $data['member_phone']])->first()) {
                throw new ApiException([0, '号码已注册']);

            }
        }

        $data['member_uuid'] = md5($data['name'].rand(1, 10000).time());
        $data['token'] = md5($data['name'].rand(1, 10000).time());
        $this->admin->addItem($data);

        return [];
    }

    /**
     * 用户登录
     * @param $data
     * @return array
     * @throws ApiException
     */
    public function loginMember($data)
    {
        $where['password'] = md5($data['password']);
        is_real_exists(@$data['name']) && $where['name'] = $data['name'];
        $field = 'id,store_id,role_id,name,name as member_name,member_uuid,token';
        $userInfo = $this->admin->getFirst($where, $field);

        if (is_null($userInfo)) {
            throw new ApiException(ApiException::ERROR_DATA_NOT_EXISTS);
        }

        $rules = $userInfo->role()
            ->selectRaw('id,role,rule_id')
            ->with('rule:id,rule,path')
            ->get()
            ->toArray();
        $rulesArray = [];
        foreach ($rules as $k => $v) {
            foreach($v['rule'] as $i => $j) {
                $j['path'] !== '' && $rulesArray[$j['path']] = $j;
            }
        }

        \Cache::set(Authenticate::CACHE_KEY.$userInfo->token, json_encode($userInfo->toArray()), 3600*24);
        \Cache::set(Authenticate::RULES_CACHE_KEY.$userInfo->token, json_encode($rulesArray), 3600*24);

        return $userInfo;
    }

    /**
     * @param $data
     * @return mixed
     */
    public function getAdminList($data)
    {
        $where = [];
        is_real_exists(@$data['member_name']) && $where['name'] = ['like', '%'.$data['member_name'].'%'];
        is_real_exists(@$data['member_email']) && $where['member_email'] = ['like', '%'.$data['member_email'].'%'];
        is_real_exists(@$data['member_phone']) && $where['member_phone'] = ['like', '%'.$data['member_phone'].'%'];
        is_real_exists(@$data['status']) && $where['status'] = $data['status'];

        return $this->admin->getAdminList($where);
    }

    /**
     * 编辑用户
     * @param $data
     * @return array
     * @throws ApiException
     */
    public function editAdmin($data)
    {
        $user = $this->admin->find($data['id']);
        if (is_null($user)) {
            throw new ApiException(ApiException::ERROR_DATA_NOT_EXISTS);
        }

        $user->update($data);

        return $user;
    }

    public function delAdmin($data)
    {
        $id = explode(',', $data['ids']);
        $success = 0;
        $fail = 0;
        $message = '';
        $update['is_delete'] = 1;
        foreach ($id as $k => $v) {
            $model = $this->admin->find($v);
            if (empty($model)) {
                $fail ++;
                $message .= '第'.($k+1).'个删除失败的原因:数据不存在;';
            } elseif ($model->member_uuid == $this->admin->getCurrentUserId()) {
                $message .= '第'.($k+1).'不能删除自己;';
            } else {
                $success ++;
                $model->delete();
            }
        }

        return ['message' => '成功删除'.$success.'个;失败'.$fail.'个;'.$message];
    }
}
